package pl.siejas.timewarper;

import java.util.Date;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.text.format.DateFormat;
import android.widget.RemoteViews;

public class TimeWarperWidget extends AppWidgetProvider {
	private Context mContext = null;
	private Handler mUpdateHandler = new Handler();
	private AppWidgetManager mAppWidgetManager;
	private RemoteViews mRemoteViews;
	private ComponentName mThisWidget;
	
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
	}
	
	@Override
	public void onDisabled(Context context) {
		super.onDisabled(context);
	}
	
	@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		mContext = context;
		mAppWidgetManager = appWidgetManager;
		mUpdateHandler.postDelayed(mUpdateRunnable, 100);
		mRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.widget);
		mThisWidget = new ComponentName(context, TimeWarperWidget.class);
    }
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		mUpdateHandler.removeCallbacks(mUpdateRunnable);
		super.onDeleted(context, appWidgetIds);
	}
	
	private Runnable mUpdateRunnable = new Runnable() {
		public void run() {
			mUpdateHandler.postDelayed(mUpdateRunnable, 25);
    		Date date = new Date();
    		date.setTime(date.getTime());
    		mRemoteViews.setTextViewText(R.id.hello_text, DateFormat.format("hh:mm:ss", date));
    		mAppWidgetManager.updateAppWidget(mThisWidget,mRemoteViews);
		}
	};
	
	

//    public static class UpdateService extends Service {
//        
//    	private long counter = 0;
//    	
////        @Override
////        public void onStart(Intent intent, int startId) {
////            handleCommand(intent);
////        }
//
//        @Override
//        public int onStartCommand(Intent intent, int flags, int startId) {
//        	RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);
//    		Date date = new Date();
//    		date.setTime(date.getTime()+counter*1000);
//    		remoteViews.setTextViewText(R.id.hello_text, DateFormat.format("hh:mm:ss", date));
//    		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
//    		ComponentName thisWidget = new ComponentName(this, TimeWrapperWidget.class);
//    		appWidgetManager.updateAppWidget(thisWidget,remoteViews);
//    		counter++;
//    		return START_STICKY_COMPATIBILITY;
//        }
//
//		@Override
//		public IBinder onBind(Intent intent) {
//			// TODO Auto-generated method stub
//			return null;
//		}
//    }
	
}
